#!/usr/bin/python
'''
Takes an AGP file and GFF file in contig orientation. Translates.
'''
import sys

# parameters.
agp_file = sys.argv[1]
gff_file = sys.argv[2]
out_file = sys.argv[3]

# read agp.
print "reading agp."
fin = open(agp_file,"rb")
lines = fin.readlines()
fin.close()

# build index.
print "building index."
contigs = {}
for line in lines:
	# tokenize.
	tmp = line.strip().split("\t")
	
	# add to dictionary.
	contigs[tmp[5]] = (int(tmp[1]), int(tmp[2]), tmp[0])
	
# read gff.
print "reading gff."
fin = open(gff_file,"rb")
lines = fin.readlines()
fin.close()

# translate.
fout = open(out_file, "wb")
for line in lines:
	# tokenize.
	tmp = line.split("\t")
	
	# look up contig.
	if tmp[0] not in contigs:
		print "bad"
		print tmp
		sys.exit()
	ent = contigs[tmp[0]]
	
	# change scaf name and coordinates.
	tmp[0] = ent[2]
	tmp[3] = str(int(tmp[3]) + ent[0])
	tmp[4] = str(int(tmp[4]) + ent[0])
	
	# print back.
	fout.write('\t'.join(tmp))
	
fout.close()
